package com.yk.system.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.crypto.SecureUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yk.common.core.constant.NumberConstant;
import com.yk.common.core.dto.SendWechatDTO;
import com.yk.common.core.utils.SendUtils;
import com.yk.system.entity.Card;
import com.yk.system.entity.CardAlarm;
import com.yk.system.entity.Gateway;
import com.yk.system.entity.UserWx;
import com.yk.system.mapper.CardAlarmMapper;
import com.yk.system.mapper.CardMapper;
import com.yk.system.mapper.GatewayMapper;
import com.yk.system.mapper.UserWxMapper;
import com.yk.system.service.CardService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * 流量卡信息表 服务类
 *
 * @author lmx
 * @since 2024-02-20
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class CardServiceImpl extends ServiceImpl<CardMapper, Card> implements CardService {

    private final SendUtils sendUtils;
    private final GatewayMapper gatewayMapper;
    private final CardAlarmMapper cardAlarmMapper;
    private final UserWxMapper userWxMapper;
    private static final String USER_ID = "141";
    private static final String API_KEY = "623530524e6cd40d9a7b202ba5a384f7";
    private static final String BASE_URL = "http://hywx.xjict.com:32040/api/v1/getChaxun";

    @Override
    public Card saveCard(String ccId, String type) {
        LambdaQueryWrapper<Card> lambda = new LambdaQueryWrapper<>();
        lambda.eq(Card::getCardno, ccId);
        Card card = this.baseMapper.selectOne(lambda);
        if (Objects.isNull(card)) {
            card = new Card();
            card.setCardno(ccId);
            card.setType(type);
            this.save(card);
        }
        return card;
    }

    @Override
    public void searchCard(Card card2) {
        List<Card> list;
        if (Objects.nonNull(card2)) {
            list = CollUtil.newArrayList(card2);
        } else {
            list = this.list();
        }
        if (CollUtil.isEmpty(list)) {
            return;
        }
        for (Card card : list) {
            // 卡号
            String cardno = card.getCardno();
            // 时间戳
            String times = String.valueOf(System.currentTimeMillis());
            // 创建MD5签名
            String signData = "userId=" + USER_ID + "&apikey=" + API_KEY + "&times=" + times;
            String sign = SecureUtil.md5(signData).toUpperCase();
            // 构造请求URL
            String urlStr = BASE_URL + "?userId=" + USER_ID + "&cardno=" + cardno + "&times=" + times + "&sign=" + sign;
            try {
                String result = HttpUtil.get(urlStr);
                JSONObject jsonObject = JSONUtil.parseObj(result);
                String code = jsonObject.getStr("code");
                if (!NumberConstant.ZERO_STR.equals(code)){
                    continue;
                }
                String dataStr = jsonObject.getStr("data");
                JSONObject data = new JSONObject(dataStr);
                card.setUsed(data.getStr("used"));
                card.setSurplus(data.getStr("surplus"));
                card.setState(data.getStr("state"));
                card.setCanused(data.getStr("canused"));
                card.setMessage(data.getStr("message"));
                card.setExpiredAt(data.getDate("expired_at"));
                String autoname = data.getStr("autoname");
                card.setAutoname(getAutoname(autoname));
                this.updateById(card);
            } catch (Exception e) {
                log.error("流量卡api异常：{}", e.getMessage());
                break;
            }
            // 是否需要报警
            double used = Double.parseDouble(card.getUsed());
            if (used < 0) {
                continue;
            }
            toAlarm(card);
        }
    }

    /**
     * 公众号推送报警
     *
     * @param card
     */
    private void toAlarm(Card card) {
        // 默认 10M
        double alarm = Double.parseDouble(card.getAlarm()) * 1024;
        // 剩余流量(单位KB)
        double surplus = Double.parseDouble(card.getSurplus());
        // 报警
        CardAlarm cardAlarm = cardAlarmMapper.selectLast(card.getCardno());
        log.info("微信公众号推送信息流量对比：[{}, {}]", alarm, surplus);
        if (surplus <= alarm) {
            if (Objects.isNull(cardAlarm) || Objects.equals(cardAlarm.getStatus(), NumberConstant.ONE_STR)) {
                SendWechatDTO dto = new SendWechatDTO();
                dto.setType(NumberConstant.TWO_STR);
                List<Gateway> gatewayList = gatewayMapper
                        .selectList(new LambdaQueryWrapper<Gateway>().eq(Gateway::getCardNumber, card.getCardno()));
                if (CollUtil.isEmpty(gatewayList)) {
                    return;
                }
                for (Gateway gateway : gatewayList) {
                    UserWx userWx = userWxMapper.selectOne(new LambdaQueryWrapper<UserWx>().eq(UserWx::getUserId, gateway.getCreatedBy()));
                    if (Objects.isNull(userWx) || CharSequenceUtil.isEmpty(userWx.getGOpenId())) {
                        return;
                    }
                    // 设备名称
                    dto.setName(gateway.getName());
                    // 告警原因
                    dto.setMsg("剩余流量为" + surplus + "KB");
                    // 告警值
                    dto.setValue(String.valueOf(alarm));
                    dto.setOpenId(userWx.getGOpenId());
                    dto.setCardno(card.getCardno());
                    dto.setSurplus(card.getSurplus());
                    dto.setUsed(card.getUsed());
                    dto.setUserId(userWx.getUserId());
                    sendUtils.sendWechatMessage(dto);
                    log.info("微信公众号推送信息成功推送消息队列");
                }
            }
        } else {
            // 恢复记录
            if (Objects.nonNull(cardAlarm) && Objects.equals(cardAlarm.getStatus(), NumberConstant.ZERO_STR)) {
                CardAlarm saveCardAlarm = new CardAlarm();
                saveCardAlarm.setAlarmMessage(cardAlarm.getAlarmMessage());
                saveCardAlarm.setCardno(cardAlarm.getCardno());
                saveCardAlarm.setCreatedAt(new Date());
                saveCardAlarm.setSurplus(card.getSurplus());
                saveCardAlarm.setUsed(card.getUsed());
                saveCardAlarm.setStatus(NumberConstant.ONE_STR);
                cardAlarmMapper.insert(saveCardAlarm);
            }
        }
    }

    /**
     * 获取运营商
     *
     * @param autoname 字符串
     * @return
     */
    private String getAutoname(String autoname) {
        if (CharSequenceUtil.isNotEmpty(autoname)) {
            // 检查字符串长度是否大于等于2
            if (autoname.length() >= 2) {
                // 截取最后两位字符
                autoname = autoname.substring(autoname.length() - 2);
            }
        }
        return autoname;
    }
}